package com.demo.afternoon;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @ClassName java_反射_动态创建对象执行方法
 * @Description TODO
 * @Author tianqinglong
 * @Date 19:28 2022/7/12
 * @Version 1.0
 **/
public class java_反射_动态创建对象执行方法 {
    public static void main(String[] args) throws Exception,ClassNotFoundException, InstantiationException, IllegalAccessException {
        Class<?> c1 = Class.forName("com.demo.afternoon.User");
     /*   User user = (User) c1.newInstance();
        System.out.println(user);

        Constructor<?> declaredConstructor = c1.getDeclaredConstructor(int.class, String.class, String.class);
        User user1 = (User) declaredConstructor.newInstance(1, "张三", "123");
        System.out.println(user1);
*/
        User user = (User) c1.newInstance();
        Method setNames = c1.getDeclaredMethod("setName", String.class);
        setNames.invoke(user,"里斯");
        System.out.println(user.getName());

        User user1 = (User) c1.newInstance();
        Field name = c1.getDeclaredField("name");
        name.setAccessible(true);
        name.set(user1,"往往");
        System.out.println(user1.getName());
    }
}
